package com.wang.tool.monitor.weaver;

import com.wang.tool.util.SimpleLogUtil;

import java.util.HashMap;
import java.util.Map;

/**
 * 类型编织器工厂
 * @author shaopeng
 * @date 2023/3/10
 */
public class TypeWeaverFactory {


    private static final Map<Class, TypeWeaver> WEAVER_MAP = new HashMap<>();


    public static <R> TypeWeaver<R> getTypeWeaver(R result) {
        if (result == null) {
            return null;
        }
        return WEAVER_MAP.get(result.getClass());
    }


    /**
     * 装载
     *
     * @param weaver
     */
    public synchronized static void install(TypeWeaver weaver) {
        if (weaver == null) {
            return;
        }
        Class point = weaver.point();
        if (point == null) {
            throw new IllegalArgumentException("typeWeaver s point can not be null");
        }
        SimpleLogUtil.info("[installMonitorTypeWeaver] point:{0}, weaver:{1}", point, weaver);
        WEAVER_MAP.put(point, weaver);
    }


    /**
     * 卸载
     *
     * @param pointClass
     */
    public synchronized static void uninstall(Class pointClass) {
        if (pointClass == null) {
            return;
        }
        if (WEAVER_MAP.remove(pointClass) != null) {
            SimpleLogUtil.info("[uninstallMonitorTypeWeaver] point:{0}", pointClass);
        }
    }


    /**
     * 清理
     */
    public synchronized static void clear() {
        WEAVER_MAP.clear();
        SimpleLogUtil.info("[clearMonitorTypeWeaver]");
    }


}
